<?php
/**
 * Description: 获取每日一题列表
 * User: devforma
 * Date: 16/3/4
 * Time: 10:12
 */

require __DIR__ . '/includes/utils.php';

class GetTopics implements iController {

    const MAX_NUM = 15;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        global $cmsdb;

        $isLoggedIn = validateUser($queryArgs) === 1;

        //根据月份获取每日一题
        if (!empty($queryArgs['month'])) {
            $ids = $this->getMonthTopics($queryArgs['month']);

        } else { //正常获取每日一题

            if (empty($queryArgs['order']) || empty($queryArgs['count']) || !filter_var($queryArgs['count'], FILTER_VALIDATE_INT)
                || !in_array($queryArgs['order'], array('forward', 'afterward'), true)
            ) {
                return genOutput(1000);
            }

            //限制列表最大数量
            $count = min($queryArgs['count'], self::MAX_NUM);

            //初始化查询语句
            $sql = 'SELECT p.ID FROM `wp_posts` AS p';
            $order = 'DESC';

            //如果给出科目查询条件,完善查询语句
            if (!empty($queryArgs['category']) && filter_var($queryArgs['category'], FILTER_VALIDATE_INT)) {
                $sql .= ' INNER JOIN `wp_term_relationships` AS t ON p.ID=t.object_id WHERE t.term_taxonomy_id=' . $queryArgs['category'];
            } else {
                $sql .= ' WHERE 1';
            }

            //如果给定了base_id,则按照base_id进行排序获取数据
            if (!empty($queryArgs['base_id']) && filter_var($queryArgs['base_id'], FILTER_VALIDATE_INT)) {
                if ($count == 1) { //只获取指定的单个每日一题
                    $sql .= " AND p.ID={$queryArgs['base_id']}";

                } else { //多个每日一题

                    //获取base_id对应的每日一题的日期
                    $date = $this->getTopicDate($queryArgs['base_id']);

                    //判断sql的比较条件
                    $comp = $queryArgs['order'] == 'forward' ? '<=' : '>=';
                    $order = $queryArgs['order'] == 'forward' ? 'DESC' : 'ASC';

                    $sql .= " AND p.post_date {$comp} '{$date}'";
                }
            }

            //完善查询语句,增加通用条件
            $sql .= " AND p.post_parent=0 AND p.post_status='publish' AND p.post_type='page' ORDER BY p.post_date {$order} LIMIT {$count}";

            $ids = $cmsdb->getCol($sql);
        }

        //无符合条件的记录,返回空数组
        if (empty($ids) || !is_array($ids))
            return genOutput(1, array('topics' => array()));

        //如果登录状态,则获取用户的收藏做题历史
        $userTopics = array();
        if ($isLoggedIn) {
            $userTopics = getUserTopics($queryArgs['user_id'], $ids);
        }

        //构造返回结果
        $list = array();
        foreach ($ids as $id) {
            $detail = getTopicDetail($id);
            if (empty($detail)) 
                continue;

            if (isset($userTopics[$id]) && $userTopics[$id]->is_store) {
                $detail['is_collected'] = true;
            }

            if (isset($userTopics[$id]) && $userTopics[$id]->wrong_time) {
                $detail['is_done'] = true;
                $detail['user_answer'] = (string)$userTopics[$id]->user_answer;
            }

            $list[$detail['date']] = $detail;
        }

        krsort($list);

        return genOutput(1, array('topics' => array_values($list)));

    }


    /**
     * 获取每日一题的发布日期
     *
     * @param $topicId
     * @return null|string
     */
    private function getTopicDate($topicId) {
        global $cmsdb;

        $sql = 'SELECT `post_date` FROM `wp_posts` WHERE `ID`=:id AND `post_parent`=0 AND `post_status`="publish" AND `post_type`="page"';

        return $cmsdb->getVar($sql, array(':id' => $topicId));
    }

    /**
     * 获取某个月的每日一题
     *
     * @param string $month 月份
     * @return array
     */
    private function getMonthTopics($month) {
        global $cmsdb;

        $nextMonth = date("Y-m", strtotime("+1 months", strtotime($month)));

        $topics = $cmsdb->getCol("SELECT `ID` FROM `wp_posts` WHERE `post_status`='publish' AND `post_parent`=0 AND 
        `post_date`>'{$month}' AND `post_date`<'{$nextMonth}' AND `post_type`='page' ORDER BY `post_date` ASC");

        return (array)$topics;
    }

}